package com.jufa_3.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jufa_3.common.R;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预检请求放过，预检请求请求方式为 PTIONS
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            //提示请先登录
            doResponse(response,R.error(4020,"请先登录！"));
        }else{
            try {
                //验证token
                JwtParser parser = Jwts.parser();
                //解析token的SigningKey必须和生成token时设置密码⼀致
                parser.setSigningKey("jufa888");
                //如果token正确（密码正确，有效期内）则正常执行，否则抛出异常
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                Claims body = claimsJws.getBody();
//                String role = body.get("role", String.class);
//                String phoneNum = body.get("phoneNum", String.class);
//                request.setAttribute("openId",openId);
//                request.setAttribute("phoneNum",phoneNum);
                return true;
            }catch (ExpiredJwtException e){
                doResponse(response,R.error(4022,"登录过期，请重新登录！"));
            }catch (UnsupportedJwtException e){
                doResponse(response,R.error(4022,"Token不合法，请自重！"));
            }catch (Exception e){
                doResponse(response,R.error(4022,"请先登录！"));
            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response, R r) throws IOException {
        response.setContentType("application/json");        //设置响应的内容类型
        response.setCharacterEncoding("utf-8");             //设置响应的内容编码方式
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(r);  //Jackson库中主要用于读取和写入Json数据的类，能够很方便地将Java对象转为Json格式的数据
        out.print(s);
        out.flush();
        out.close();
    }
}
